package megalopolis.client;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import javax.swing.*;

/**
 * User: Kirill
 * Date: 21.02.2008
 */
public class LoginDialog extends JDialog implements ActionListener {

	private boolean logined;

	private JTextField login;

	private JTextField password;

	private JButton loginButton;

	private JButton cancelButton;

	private JPanel loginPanel;

	private Controller controller;

	public LoginDialog(JFrame frame, Controller controller) {
		super(frame, "Login", true);

		this.controller = controller;

		loginPanel = new JPanel(new GridLayout(3, 2));
		loginPanel.add(new JLabel("Login:"));
		loginPanel.add(login = new JTextField());
		loginPanel.add(new JLabel("Password:"));
		loginPanel.add(password = new JTextField());
		loginPanel.add(loginButton = new JButton("login"));
		loginPanel.add(cancelButton = new JButton("cancel"));
		loginButton.addActionListener(this);
		cancelButton.addActionListener(this);

		getContentPane().add(loginPanel);

		logined = false;

		setSize(200, 300);
		setLocationRelativeTo(null);
	}

	public boolean isLogined() {
		return logined;
	}

	public void actionPerformed(ActionEvent e) {
		Object src = e.getSource();
		if (src == loginButton) {
			loginPanel.setEnabled(false);
			try {
				logined = controller.login(login.getText(), password.getText());
			} catch (IOException e1) {
				controller.reportException(e1);
			}
			if (logined) {
				dispose();
			} else {
				loginPanel.setEnabled(true);
			}
		} else if (src == cancelButton) {
			dispose();
		}
	}

}
